package com.sihan.framework.etm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.framework.mybatis.service.impl.BaseServiceImpl;
import com.sihan.framework.etm.common.cache.LocalCache;
import com.sihan.framework.etm.common.websocket.WebSocketUtil;
import com.sihan.framework.etm.common.websocket.WsSessionManager;
import com.sihan.framework.etm.entity.PushAnomalyRecord;
import com.sihan.framework.etm.entity.baseData.DeviceModel;
import com.sihan.framework.etm.mapper.PushAnomalyRecordMapper;
import com.sihan.framework.etm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sihan.framework.etm.service.PushAnomalyRecordService;

import java.util.*;

@Service
@Slf4j
public class PushAnomalyRecordServiceImpl extends BaseServiceImpl<PushAnomalyRecord, String> implements PushAnomalyRecordService {
    @Autowired
    private PushAnomalyRecordMapper pushAnomalyRecordMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private WebSocketUtil webSocketUtil;




    /**
     * *根据设备信息与 异常类型添加推送记录
     * @param dev 设备信息
     * @param topic 异常类型
     * @param msg 异常具体信息
     * @return boolean 类型
     */
    @Override
    public void addPushRecord(DeviceModel dev, String date,String topic,String msg) {
        List<String> li = new ArrayList<>();
        if (null != dev.getOrgId() && !"".equals(dev.getOrgId())){
            //获取组织下 所有在线人员的 sessionId
            li = userService.getSessionIdfindByOrgId(dev.getOrgId());
        }
        //如果没有用户 不添加 直接返回
        if (li.size() < 1){
            return ;
        }
        //判断 推送时间 降低推送频率 30秒内 相同异常不再提示
        if(LocalCache.containsKey(topic+dev.getId())){
            if (new Date().getTime() - Long.parseLong(Objects.requireNonNull(LocalCache.get(topic + dev.getId())))< 30000){
                return;
            }
        }
        LocalCache.put(topic+dev.getId(), String.valueOf(new Date().getTime()),600);
        for (String s :li){
            Map<String,Object> map = new HashMap<>();
            map.put("deviceCode",dev.getCode());
            map.put("deviceName",dev.getName());
            map.put("date",date);
            map.put("msg",msg);
            JSONObject json = new JSONObject(map);
            try {
                if(null != WsSessionManager.get(s)){
                    webSocketUtil.sendMsg(json.toJSONString(),s);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.info("异常提醒出现错误:{},人员session:{}",json.toJSONString(),s);
            }
            log.info("异常提醒:{}",json.toJSONString());
        }

    }

    /**
     * 根据用户 id查询未推送异常提示
     * @param userId
     * @return
     */
    @Override
    public List<PushAnomalyRecord> pushList(String userId) {
        return null;
    }


}
